package cn.qicaiwang.open.qxyApi.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class SignUtil {

    /**
     * 生成MD5签名
     */
    public static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(digest);
    }

    /**
     * 生成Base64编码
     */
    public static String base64Encode(String input) {
        byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
        return Base64.getEncoder().encodeToString(inputBytes);
    }

    /**
     * 生成请求签名
     * @param appKey 应用Key
     * @param appSecret 应用密钥
     * @param accessToken 访问令牌
     * @param reqDate 请求时间戳
     * @param requestBody 请求体内容
     * @return 完整的签名
     */
    public static String generateSign(String appKey, String appSecret,
                                      String accessToken, String reqDate,
                                      String requestBody) throws NoSuchAlgorithmException {
        // 计算请求体MD5
        String contentMd5 = md5(requestBody);

        // 生成待签名字符串
        String toSign = "POST_" + contentMd5 + "_" + reqDate + "_" + accessToken + "_" + appSecret;

        // 生成MD5签名
        String md5Result = md5(toSign);

        // 生成Base64编码
        String base64Result = base64Encode(md5Result);

        // 最终签名格式
        return "API-SV1:" + appKey + ":" + base64Result;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}